package com.androidx.paging.diffutil

import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.databinding.DataBindingUtil
import androidx.recyclerview.widget.DiffUtil
import com.androidx.paging.model.GoodsModel
import com.androidx.paging.R
import com.androidx.paging.databinding.ActivityDiffBinding
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken

/**
 * Created by zhangyuncai on 2020/8/12.
 */
class DiffActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_diff)

        val binding =
            DataBindingUtil.setContentView<ActivityDiffBinding>(this, R.layout.activity_diff)

        val oldList = mutableListOf<GoodsModel>()
        for (index in 0..4) {
            oldList.add(GoodsModel().apply {
                id = index
                name = "商品:${index}"
            })
        }
        val gson = Gson()
        val type=object :TypeToken<MutableList<GoodsModel>>(){}.type
       val newList= gson.fromJson<MutableList<GoodsModel>>(gson.toJson(oldList),type)
        val diffAdapter = DiffAdapter(oldList)
        binding.rvDiff.adapter = diffAdapter
        binding.change.setOnClickListener {
//            val newList = mutableListOf<GoodsModel>()
//            newList.addAll(oldList)
//            for (goodsModel in newList) {
//
//            }
            newList[0].name="我被修改了"
//            for (index in 0 until oldList.size) {
//                if (index % 2 == 0) {
//                    newList.add(oldList[index])
//                }
//            }
//            for (index in 5..6) {
//                newList.add(GoodsModel().apply {
//                    id = index
//                    name = "新增商品:${index}"
//                })
//            }
            diffAdapter.list=newList
            val calculateDiff = DiffUtil.calculateDiff(MyDiffCallback(oldList, newList))
            calculateDiff.dispatchUpdatesTo(diffAdapter)
//            diffAdapter.list=newList
//            diffAdapter.notifyDataSetChanged()
        }
    }
}